<template>
  <el-upload :on-preview="handlePreview"
    :on-progress="handleProgress"
    :before-upload="handelBeforeUpload"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    :on-error="handleError"
    :on-exceed="handleExceed"
    action="#"
    :data="uploadData"
    :file-list="value"
    :type="type"
    :list-type="listType"
    :multiple="multiple"
    :show-file-list="showFileList"
    :accept="accept"
    :limit="limit"
    :http-request="uploadHttpRequest"
    :limitSize="limitSize">
    <i class="el-icon-plus"></i>
    <el-button v-if="!$slots.default"
      :disabled="disabledUpload"
      size="small"
      type="primary"
      :loading="isLoading">
      {{buttonLabel}}
    </el-button>
     <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <!-- <div class="el-upload__tip"
      slot="tip">
      <slot name="tip">
        <span v-if="!$slots.default">{{remind}}</span>
      </slot>
    </div> -->
    <slot>
    </slot>
  </el-upload>
</template>

<script>
export default {
  name:'Upload',
  // 按照字母顺序排列各类属性
  mounted(){
    console.log('this.$store.state',this.$store.state);
  },
  computed: {
    remind() {
      return this.singleFile ? "只能上传一个文件" : "可上传多个文件";
    },
    disabledUpload() {
      return (
        this.disabled ||
        (this.singleFile && this.value.length > 0) ||
        !!(this.max && this.value.length > this.max - 1)
      );
    },
    isLoading() {
      return this.loading;
    }
  },
  // 页面数据
  data() {
    return {
      action: "",
      uploadData: {},
      maxDisabled: false,
      dialogVisible:false,
      path:'',
      Arr:[]
    };
  },
  // 页面方法
  methods: {
    uuid() {
      let chars = "abcdef0123456789";
      let maxPos = chars.length;
      let id = "";
      for (let i = 0; i < 32; i++) {
        id += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return id;
    },
    getUrl(urlString) {
      let start = urlString.indexOf("<Location>") + 10;
      let end = urlString.indexOf("</Location>");
      return urlString.substr(start, end - start);
    },
    /**
     * 在BeforeUpload回调是，file.uid 是 undefined。所以使用lastModified
     */
    handleProgress(...args) {
      this.$emit("progress", ...args);
    },
    handelBeforeUpload(file) {
     let fileName=file.name.substring(file.name.lastIndexOf('.')+1)
     let fileType = ".gif|.jpeg|.jpg|.png|.svg|";
      if (fileType.indexOf(fileName + "|") == "-1") {
        this.$message({
          type: "error",
          message: "不支持此格式文件上传"
        });
        return false
      } else {
        
      }
     
    },
    uploadHttpRequest(file){
       let _self = this;
      const isLimit = (file.file.size / 1024) > this.limitSize;
      // console.log('file.size / 1024',(file.file.size / 1024))
      if (isLimit) {
        this.$message({
          type: "error",
          message: "上传文件大小不能超过 20M!"
        });
      } else {
        return new Promise(function(resolve, reject) {
          var formFile = new FormData();
          formFile.append('img',file.file);  
          //  console.log("file11", file.file);
         
          _self.$axios.post('upImage',formFile).then(res => {
             // console.log('res',res.data.path)
              if (res.data) {
                _self.path=res.data.path
               _self.$message.success('上传成功')
                resolve(true);
              } else {
                _self.$message({
                  type: "error",
                  message: '上传失败'
                });
              }
            })
            .catch(err => {
              console.log('err',err)
              _self.$message({
                type: "error",
                message: "出错了"
              });
              
            });
        });
      }
      return isLimit;
    },
    /**
     * response 请求response
     * file 新增的文件
     * fileList 已上传文件列表
     */
    handleSuccess(response, file, fileList) {
      /**
       * 当上传多个文件时,如果直接 $emit('success').
       * onSuccess 再进行 fileList.push(file).
       * 会报错 Uncaught TypeError: Cannot set property 'status' of null.
       */
      console.log('fileList', fileList.length)
      let arr=[]
      arr=fileList[fileList.length-1]={
        ...fileList[fileList.length-1],
        path:this.path
      }
     
      // console.log('fileList',fileList);
      setTimeout(() => {
        this.$emit("success", file, response, fileList);
      }, 1);
     
    },
    handleRemove(file) {
      console.log("file", file);
      if (file && file.response) {
        this.$emit("remove", file, file.response.data);
      } else if (!file) {
        this.$emit("remove", file);
      } else {
        this.$emit("remove", file, file.url);
      }
    },
    handlePreview(file) {
      console.log('yulan');
      console.log('file-url',file)
      let filetype = file.url.substring(file.url.lastIndexOf(".") + 1);
      if (
        filetype === "doc" ||
        filetype === "docx" ||
        filetype === "xls" ||
        filetype === "xlsx" ||
        filetype === "ppt" ||
        filetype === "pptx"
      ) {
        window.open(
          "https://view.officeapps.live.com/op/view.aspx?src=" +
            encodeURIComponent(file.url)
        );
      } else {
        window.open(file.url);
      }
    },
    handleError(error, response, file) {
      this.$message.error(`上传${file.name}失败，请重新上传。`);
      console.log("handleError ", error, response, file);
    },
    // 文件超出限制
    handleExceed(files, fileList){
      // console.log('files, fileList',files, fileList);
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  },
  // 组件属性
  props: {
    value: {
      type: Array,
      default() {
        return [];
      }
    },
    singleFile: {
      type: Boolean,
      default: false
    },
    bucketName: {
      type: String,
      default: ""
    },
    listType: {
      type: String,
      default: "picture-card"
    },
    type: {
      type: String,
      default: "select"
    },
    multiple: {
      type: Boolean,
      default: false
    },
    showFileList: {
      type: Boolean,
      default: true
    },
    accept: {
      type: String,
      default: ""
    },
    limitSize: {
      type: Number,
      default: 20480
    },
    buttonLabel: {
      type: String,
      default: "点击上传"
    },
    disabled: {
      type: Boolean,
      default: false
    },
    max: {
      type: Number,
      default: 0
    },
    limit: {
      type: Number,
      default: 200
    },
    loading: {  
      type: Boolean,
      default: false
    },
    baseApi: {
      type: String,
      default: "/upload/coldchainImage"
    }
  }
};
</script>

<style>

</style>
